<template>
  <div class="app-container">
    <!-- 筛选栏 -->
    <div v-show="showSearch">
      <!-- 搜索表单 -->
      <el-form :inline="true" ref="queryForm" size="small">
        <el-form-item label="试卷标题">
          <el-input
            v-model="queryForm.title"
            placeholder="请输入试卷标题"
            clearable
          ></el-input>
        </el-form-item>
        <!-- 级联方式分类选择 -->
        <el-form-item label="适用工种">
          <div class="block">
            <el-cascader
              v-model="queryForm.courseId"
              :options="typeOptions"
              placeholder="默认全部"
              :props="{
                value: 'id',
                label: 'courseName',
                children: 'childrenList',
                expandTrigger: 'hover',
              }"
              :show-all-levels="false"
              clearable
            ></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="适用职级">
          <el-select
            v-model="queryForm.gradeId"
            clearable
            placeholder="默认全部"
          >
            <el-option
              v-for="item in gradeList"
              :key="item.id"
              :label="item.grade"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学习路线">
          <el-select v-model="queryForm.kind" clearable placeholder="默认全部">
            <el-option
              v-for="item in kindList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="queryTest"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格上方按钮 -->
    <div>
      <div style="float: left; margin-bottom: 10px">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="small"
          @click="preAdd"
          >新增试卷</el-button
        >
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="small"
          @click="deleteList"
          >批量删除</el-button
        >
      </div>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="queryTest"
        style="float: right"
      ></right-toolbar>
    </div>
    <!-- 信息列表 -->
    <div style="float: left; width: 100%">
      <el-table
        border
        v-loading="listLoading"
        :header-cell-style="{ background: '#FAFAFA' }"
        :data="testPaperList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
        height="75vh"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <!-- <el-table-column
          prop="eduTestId"
          label="id"
          :show-overflow-tooltip="true"
        >
        </el-table-column> -->
        <el-table-column prop="eduTestInfo.title" label="标题">
        </el-table-column>
        <el-table-column prop="courseName" label="适用工种"> </el-table-column>
        <el-table-column prop="grade" label="适用职级"> </el-table-column>
        <el-table-column prop="eduTestInfo.kind" label="类型">
          <template slot-scope="scope">
            <span v-if="scope.row.eduTestInfo.kind === '0'">新型学徒</span>
            <span v-else-if="scope.row.eduTestInfo.kind === '1'">重点用工</span>
            <span v-else-if="scope.row.eduTestInfo.kind === '2'">技能提升</span>
          </template>
        </el-table-column>
        <el-table-column prop="eduTestInfo.limitTime" label="限时(分钟)">
        </el-table-column>
        <el-table-column prop="eduTestInfo.totalScore" label="总分">
        </el-table-column>
        <el-table-column
          prop="gmtCreate"
          label="创建时间"
          :show-overflow-tooltip="true"
          sortable
        >
        </el-table-column>
        <el-table-column
          prop="gmtModified"
          label="最后修改时间"
          :show-overflow-tooltip="true"
          sortable
        >
        </el-table-column>
        <el-table-column label="是否发布" align="center" key="status">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.testStatus"
              active-text="是"
              inactive-text="否"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="modify(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="medium" @click="deleteOne(scope.row)">
              删除
            </el-button>
            <el-button
              type="text"
              size="medium"
              @click="viewQuestion(scope.row)"
            >
              查看题目
            </el-button>
            <el-button type="text" size="medium" @click="viewRecord(scope.row)">
              查看做题记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="width: 100%; text-align: center; margin-top: 10px">
        <el-pagination
          @size-change="sizeChange"
          @current-change="goto"
          :current-page="page.current"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          background
          style="float: right"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 新增对话框 -->
    <el-dialog
      title="新增试卷"
      :visible.sync="addDialog"
      width="40%"
      :before-close="handleClose"
    >
      <el-form ref="form" :rules="rules" :model="addForm" label-width="100px">
        <el-row>
          <el-form-item label="试卷标题" prop="title">
            <el-input
              v-model="addForm.title"
              placeholder="请输入试卷标题"
              maxlength="30"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="适用工种" prop="courseId">
              <el-cascader
                v-model="addForm.courseId"
                :options="typeOptions"
                :props="{
                  value: 'id',
                  label: 'courseName',
                  children: 'childrenList',
                  expandTrigger: 'hover',
                }"
                :show-all-levels="false"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="medium" label="适用职级" prop="gradeId">
              <el-select v-model="addForm.gradeId" placeholder="请选择">
                <el-option
                  v-for="item in gradeList"
                  :key="item.id"
                  :label="item.grade"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="限时(分钟)" prop="limitTime">
              <el-input-number
                v-model="addForm.limitTime"
                :min="1"
              ></el-input-number> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="试卷总分" prop="totalScore">
              <el-input-number
                v-model="addForm.totalScore"
                label="分"
                :min="1"
              ></el-input-number> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-form-item label="类型" prop="kind">
            <el-select
              v-model="addForm.kind"
              clearable
              placeholder="请选择类型"
            >
              <el-option
                v-for="item in kindList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addTestPaper">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      title="试卷信息修改"
      :visible.sync="modifyDialog"
      width="40%"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        :rules="rules"
        :model="modifyForm"
        label-width="100px"
      >
        <el-row>
          <el-form-item label="试卷标题" prop="title">
            <el-input
              v-model="modifyForm.title"
              placeholder="请输入试卷标题"
              maxlength="30"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="适用工种" prop="courseId">
              <el-cascader
                v-model="modifyForm.courseId"
                :options="typeOptions"
                :props="{
                  value: 'id',
                  label: 'courseName',
                  children: 'childrenList',
                  expandTrigger: 'hover',
                }"
                :show-all-levels="false"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item size="medium" label="适用职级" prop="gradeId">
              <el-select v-model="modifyForm.gradeId" placeholder="请选择">
                <el-option
                  v-for="item in gradeList"
                  :key="item.id"
                  :label="item.grade"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="限时(分钟)" prop="limitTime">
              <el-input-number
                v-model="modifyForm.limitTime"
                :min="1"
              ></el-input-number> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="试卷总分" prop="totalScore">
              <el-input-number
                v-model="modifyForm.totalScore"
                label="分"
                :min="1"
              ></el-input-number> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-form-item label="类型" prop="kind">
            <el-select
              v-model="modifyForm.kind"
              clearable
              placeholder="请选择类型"
            >
              <el-option
                v-for="item in kindList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="update()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  deleteTest,
  addTest,
  updateTestStatus,
  updateTest,
  queryTestPaperList,
} from "@/api/testPaper";
import { getCategory } from "@/api/classification";
import { mapGetters } from "vuex";
import { getGradeList } from "@/api/grade";
export default {
  //试卷列表
  name: "testPaper",
  computed: {
    ...mapGetters(["companyId"]),
  },
  data: function () {
    return {
      //表格加载遮罩
      listLoading: "false",
      //级联分类列表
      typeOptions: [],
      //搜索表单
      queryForm: {
        title: "",
        gradeId: "",
        courseId: "",
        kind: "",
        type: "0",
      },
      //类型列表
      kindList: [
        { value: "0", label: "新型学徒" },
        {
          value: "1",
          label: "重点用工",
        },
        {
          value: "2",
          label: "技能提升",
        },
      ],
      //职级列表
      gradeList: [],
      //分页设置
      page: {
        current: 1,
        total: 0,
        size: 10,
      },
      //试卷列表
      testPaperList: [],
      //批量删除列表
      selectList: [],
      //新增试卷对话框
      addDialog: false,
      //新增试卷的表单
      addForm: {},
      //修改试卷的对话框
      modifyDialog: false,
      //修改试卷的id
      modifyId: "",
      //修改试卷的表单
      modifyForm: {
        courseId: "",
        gradeId: "",
        limitTime: "",
        title: "",
        totalScore: "",
      },
      //是否显示搜索表单
      showSearch: true,
      //表单验证
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        courseId: [{ required: true, message: "请选择工种", trigger: "blur" }],
        gradeId: [
          { required: true, message: "请选择适用职级", trigger: "blur" },
        ],
        limitTime: [{ required: true, message: "请输入限时", trigger: "blur" }],
        totalScore: [
          { required: true, message: "请输入总分", trigger: "blur" },
        ],
        kind: [{ required: true, message: "请选择类型", trigger: "blur" }],
      },
    };
  },
  created: function () {
    this.queryTest();
    //获取职级列表
    getGradeList().then((res) => {
      const data = res.data;
      this.gradeList = data.resList;
    });
  },
  methods: {
    //查找试卷列表
    queryTest: function () {
      let params = this.queryForm;
      if (this.queryForm.courseId.length > 0) {
        params.courseId =
          this.queryForm.courseId[this.queryForm.courseId.length - 1];
      }
      let that = this;
      this.listLoading = true;
      //表格数据
      queryTestPaperList(
        params,
        this.page.current,
        this.page.size,
        this.companyId
      ).then((res) => {
        const data = res.data;
        that.page.total = data.total;
        that.testPaperList = data.resList;
        this.listLoading = false;
      });
      //分类列表
      getCategory(0, this.companyId).then((res) => {
        const data = res.data;
        this.typeOptions = this.deleteChildren(data.resList);
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryForm = {
        title: "",
        gradeId: "",
        courseId: "",
        kind: "",
        type: "0",
      };
      this.queryTest();
    },
    //删除类别中的空childrenList[]
    deleteChildren(arr) {
      let childs = arr;
      for (let i = childs.length; i--; i > 0) {
        if (childs[i].childrenList) {
          if (childs[i].childrenList.length) {
            this.deleteChildren(childs[i].childrenList);
          } else {
            delete childs[i].childrenList;
          }
        }
      }
      return arr;
    },
    //新增预处理
    preAdd() {
      this.addForm = {
        title: "",
        courseId: "", //类别id
        gradeId: "0", //等级id
        limitTime: 0,
        totalScore: 0,
        kind: "0",
      };
      if (this.$refs["form"] !== undefined) {
        this.$refs["form"].resetFields();
      }
      this.addDialog = true;
    },
    //新增试卷
    addTestPaper() {
      //0代表试卷
      this.addForm.type = "0";
      let that = this;
      if (this.addForm.title == "") {
        this.$message({
          message: "请填写标题",
          type: "warning",
        });
      } else if (this.addForm.courseId == "") {
        this.$message({
          message: "请选择工种",
          type: "warning",
        });
      } else {
        that.addForm.courseId =
          that.addForm.courseId[that.addForm.courseId.length - 1];
        addTest(this.addForm).then((res) => {
          if (res.success == true) {
            this.$message({
              message: "提交成功",
              type: "success",
            });
            that.queryTest();
            that.addDialog = false;
          } else {
            this.$message({
              message: "提交失败",
              type: "error",
            });
          }
        });
      }
    },
    //关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },

    //试卷发布状态修改
    handleStatusChange(row) {
      updateTestStatus(row.eduTestId, row.testStatus).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
      });
    },
    //删除单份试卷
    deleteOne: function (row) {
      var self = this;
      this.$confirm("此操作将删除该试卷, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = []; //删除列表
          idArray.push(row.eduTestId);
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //选择删除的id列表
    handleSelectionChange: function (val) {
      this.selectList = val;
    },
    //删除多份试卷
    deleteList: function () {
      if (this.selectList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      var self = this;
      this.$confirm("此操作将删除选中的所有试卷, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = [];
          self.selectList.forEach(function (testPaper, index) {
            idArray.push(testPaper.eduTestId);
          });
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //删除的Ajax请求
    deleteAjax: function (idArray) {
      var that = this;
      deleteTest(idArray).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          that.queryTest();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    //修改预处理
    modify(row) {
      this.modifyForm = row.eduTestInfo;
      this.modifyId = row.eduTestId;
      this.modifyDialog = true;
    },
    //提交修改
    update() {
      let that = this;
      if (this.modifyForm.title == "") {
        this.$message({
          message: "标题不能为空",
          type: "warning",
        });
      } else {
        if (that.modifyForm.courseId.length == 2) {
          that.modifyForm.courseId =
            that.modifyForm.courseId[that.modifyForm.courseId.length - 1];
        } else if (that.modifyForm.courseId.length == 1) {
          that.modifyForm.courseId = that.modifyForm.courseId[0];
        }
        updateTest(this.modifyForm, this.modifyId).then((res) => {
          if (res.success == true) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            that.queryTest();
            that.modifyDialog = false;
          } else {
            this.$message({
              message: "修改失败",
              type: "error",
            });
          }
        });
      }
    },
    //查看试卷题目
    viewQuestion: function (testPaper) {
      this.$router.push({
        name: "Question2",
        query: {
          id: testPaper.eduTestId,
          title: testPaper.eduTestInfo.title,
          totalScore: testPaper.eduTestInfo.totalScore,
        },
      });
    },
    //查看做题记录
    viewRecord: function (testPaper) {
      this.$router.push({
        name: "TestRecord",
        query: {
          id: testPaper.eduTestId,
          title: testPaper.eduTestInfo.title,
          totalScore: testPaper.eduTestInfo.totalScore,
        },
      });
    },
    //跳转页面
    goto: function (current) {
      this.page.current = current;
      this.queryTest();
    },
    //页码改变
    sizeChange: function (size) {
      this.page.size = size;
      this.queryTest();
    },
  },
};
</script>

<style scoped>
</style>
